package org.bsc.mgwt.client.widget.base;

import com.google.gwt.i18n.client.HasDirection.Direction;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;
import com.googlecode.mgwt.ui.client.widget.LayoutPanel;

/**
 * 
 * @author bsorrentino
 *
 * @param <W>
 * @param <S>
 */
public abstract class MLabeledWidget<W extends Widget, S extends CssResource> extends Composite implements HasLabel  {

	protected W wrapped;
	protected final Label label = new Label();
	protected final LayoutPanel main = new LayoutPanel();

	/**
	 * 
	 */
	protected MLabeledWidget() {
		this( (S)null );
	}
	
	/**
	 * 
	 * @param wrapped
	 * @param css
	 */
	protected MLabeledWidget(S css) {
		if( css!=null ) css.ensureInjected();

		this.wrapped = initWidget( css );
		
		if( null==wrapped ) throw new IllegalStateException( "widget to wrap is null!");
		
		this.wrapped.getElement().setAttribute("mtype", "input");
		this.label.getElement().setAttribute("mtype", "label");
		
		setLabelStyle( false );
		
		main.add(label);
		main.add(wrapped);
		
		initWidget(main);
	}

	/**
	 * 
	 * @return
	 */
	public final W unwrap() {
		return wrapped;
	}
	
	protected abstract W initWidget( S css );
	
	@Override
	public String getLabel() {
		return label.getText();
	}

	@Override
	public void setLabel(String value) {
		label.setText(value);
	}
	
	@Override
	public void setLabel(String value, Direction dir) {
		label.setText(value, dir);	
	}

	@Override
	public void setLabelStyle(boolean horizontal) {
	}

	public void setHorizontal(boolean horizontal) {
		setLabelStyle( horizontal );
		main.setHorizontal(horizontal);
	}

}
